<template>
  <base-breadcrumb>
    <!-- 搜索 -->
    <searchData
      :searchData="searchArr"
      @search="search"
    ></searchData>
    <!-- 表格 -->
    <a-card :bordered="false">
      <list-table
        ref="table"
        :columns="columns"
        :request="loadData"
      >
        <template
          slot="action"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
              v-btn-permission="'hse_002_loo_04'"
              @click="handleManage(record, 'look')"
            >查看</a>
            <a
              v-btn-permission="'hse_002_edi_02'"
              @click="handleManage(record, 'edit')"
              v-if="hideBuquBtn()"
            >编辑</a>
            <a
              v-btn-permission="'hse_002_dln_05'"
              @click="exportPointInfo(record.id )"
            >下载</a>
            <a
              v-btn-permission="'hse_002_del_03'"
              @click="handleDelete(record)"
              v-if="hideBuquBtn()"
            >删除</a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import CollapseStatic from '@/views/quality/components/CollapseStatic' // 汇总
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import OrgTreeSelect from '@/components/OrgTreeSelect'
import rectifyNoticeApi from '@/api/safetySupervision/checkAndRectify/rectifyNotice'
import { saveAs } from 'file-saver'

export default {
  name: 'a' + Date.now(),
  components: {
    CollapseStatic
  },
  data() {
    return {
      searchArr: [
        // { name: '所属分公司', type: SelectSubCompany, valueKey: 'branchComId' },
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // { name: '所属项目', type: SelectProject, valueKey: 'projectId', keyValue: 'branchComId' }
      ],
      columns: [
        { title: '整改单编号', dataIndex: 'number', width: 120 },
        { title: '所属分公司', dataIndex: 'branchComName', width: 200 },
        { title: '所属项目', ellipsis: true, dataIndex: 'projectName', width: 200 },
        { title: '隐患数量', dataIndex: 'dangerSize', width: 100 },
        { title: '检查人', dataIndex: 'inspectName', width: 100 },
        { title: '责任分包单位', dataIndex: 'subcontractorName', width: 200 },
        { title: '整改状态', dataIndex: 'rectificationStatus', width: 100 },
        { title: '创建时间', dataIndex: 'createTime', width: 200 },
        { title: '打印状态', dataIndex: 'printStatus', width: 100 },
        {
          title: '操作',
          dataIndex: 'action',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      btnVal: 0,
      queryParam: {}, // 查询参数

      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const q = Object.assign({}, parameter, { query: this.queryParam })
        return rectifyNoticeApi.findListByMain({}, q)
      }
    }
  },
  methods: {
    async exportPointInfo(id) {
      /**
       * jquery.wordexport.js源码——START
       */
      var statics = {
        mhtml: {
          top:
            'Mime-Version: 1.0\nContent-Base: ' +
            location.href +
            '\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
            location.href +
            '\n\n<!DOCTYPE html>\n<html>\n_html_</html>',
          head: '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n',
          body: '<body>_body_</body>'
        }
      }
      var options = {
        maxWidth: 200
      }
      // Embed all images using Data URLs
      var images = Array()
      let res = await rectifyNoticeApi.printDown({ id })
      let innerHTML = res.data.content
      let el = document.createElement('div')
      el.innerHTML = innerHTML
      let img = el.getElementsByTagName('img')
      var reg = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i
      for (var i = 0; i < img.length; i++) {
        let uri
        // 如果是base64格式输出该base64
        if (reg.test(img[i].src)) {
          // Calculate dimensions of output image
          const { width, height } = await new Promise((resolve) => {
            const im = new Image()
            im.crossOrigin = ''
            im.src = img[i].src
            im.onload = function () {
              resolve(im)
            }
          })
          var w = options.maxWidth
          var h = height * (w / width)
          // Create canvas for converting image to data URL
          uri =
            i == 0
              ? img[i].src
              : await new Promise((resolve) => {
                  var canvas = document.createElement('CANVAS')
                  canvas.width = w
                  canvas.height = h
                  // Draw image to canvas
                  var context = canvas.getContext('2d')
                  context.drawImage(img[i], 0, 0, w, h)
                  resolve(canvas.toDataURL('image/png/jpg'))
                })
          innerHTML = innerHTML.replace(img[i].src, uri)
          // Get data URL encoding of image
          // $(img[i]).attr('src', img[i].src)
          // img[i].src = uri
          img[i].width = w
          img[i].height = h
        }
        // console.log(uri)
        // Save encoded image to array
        images[i] = {
          type: uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')),
          encoding: uri.substring(uri.indexOf(';') + 1, uri.indexOf(',')),
          location: uri,
          data: uri.substring(uri.indexOf(',') + 1)
        }
      }
      var mhtmlBottom = '\n'
      for (var i = 0; i < images.length; i++) {
        mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n'
        mhtmlBottom += 'Content-Location: ' + images[i].location + '\n'
        mhtmlBottom += 'Content-Type: ' + images[i].type + '\n'
        mhtmlBottom += 'Content-Transfer-Encoding: ' + images[i].encoding + '\n\n'
        mhtmlBottom += images[i].data + '\n\n'
      }
      mhtmlBottom += '--NEXT.ITEM-BOUNDARY--'

      var styles = ''
      // Aggregate parts of the file together
      var fileContent = statics.mhtml.top.replace('_html_', statics.mhtml.head.replace('_styles_', styles) + statics.mhtml.body.replace('_body_', innerHTML)) + mhtmlBottom

      // Create a Blob with the file contents
      var blob = new Blob([fileContent], {
        type: 'application/msword;charset=utf-8'
      })
      saveAs(blob, '整改通知单.doc')
      this.$refs.table.refresh()
    },
    async download(id) {
      await rectifyNoticeApi.download({ id })
      this.$refs.table.refresh()
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh()
    },
    /**
     * 操作栏
     */
    handleManage(record, pageType) {
      this.$router.push({
        path: '/safetySupervision/checkAndRectify/rectifyNotice/edit',
        query: {
          id: record.id,
          pageType
        }
      })
    },
    /**
     * 删除记录
     */
    handleDelete(e) {
      this.$delList3(
        rectifyNoticeApi.del,
        () => {
          this.search()
        },
        { id: e.id }
      )
    }
  }
}
</script>


